package com.jiangjun.fetch.servlet;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jiangjun.fetch.mongo.MongoDBSupport;
import com.jiangjun.fetch.util.Page;
import com.jiangjun.fetch.util.ResponseSender;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;

@WebServlet(name = "GetInfoList4WeiboServlet", urlPatterns = "/getInfoList4WeiboService", asyncSupported = false)
@WebInitParam(name = "default_charset", value = "utf-8")
public class GetInfoList4WeiboServlet extends HttpServlet {

	@Override
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub

		/**
		 * 一页取20条
		 */
		String type = request.getParameter("type");// 1是文本，2是图片
		String currentpage = request.getParameter("cpage");
		MongoDBSupport mongoDBSupport = MongoDBSupport.getInstance();
		String collectionName = MongoDBSupport._FETCHWEIBO;
		Page page = new Page(20, Integer.parseInt(currentpage));
		BasicDBObject sort = new BasicDBObject();
		sort.put("date", -1);
		BasicDBObject param = new BasicDBObject();
		param.put("type", type);
		param.put("isEnable", "1");
		DBCursor cursor = mongoDBSupport.queryCollectionByParam(collectionName,
				page, param, sort);
		List<DBObject> list = cursor.toArray();
		for (DBObject object : list) {
			if(null != object.get("date"))
			{
				String date = object.get("date").toString();
				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");//设置日期格式
				date = df.format(Long.parseLong(date));
				object.put("date", date);
			}
			if (null != object.get("img_path")) {
				String img_path = object.get("img_path").toString();
				if (img_path.indexOf(";") > -1) {
					StringBuffer sb = new StringBuffer();
					String[] array = img_path.split(";");
					for (String s : array) {
						if (sb.toString().equals("")) {
							sb.append(Start.img_server + s);
						} else {
							sb.append(";");
							sb.append(Start.img_server + s);
						}
					}
					object.put("img_path", sb.toString());
				} else {
					object.put("img_path",
							Start.img_server
									+ object.get("img_path").toString());
				}

			}
		}
		String content = list.toString();
		ResponseSender.sendResponse(response, content.getBytes("utf-8"),
				"utf-8", null);
	}
}
